package cn.aitrox.ry.app.web.controller.auth;

import cn.aitrox.ry.app.web.vo.auth.role.out.AuthRoleDetailOutVo;
import cn.aitrox.ry.app.web.vo.auth.user.role.in.AuthUserRoleUpdateInVo;
import cn.aitrox.ry.app.web.vo.auth.user.role.out.AuthUserRoleDetailOutVo;
import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.common.service.api.dto.User;
import cn.aitrox.ry.service.auth.dto.user.role.in.AuthUserRoleUpdateInDto;
import cn.aitrox.ry.service.auth.dto.user.role.out.AuthUserRoleDetailDto;
import cn.aitrox.ry.service.auth.feign.AuthUserRoleFeign;
import cn.aitrox.ry.service.user.feign.UserFeign;
import cn.aitrox.ry.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class AuthUserRoleController {

    @Autowired
    @Lazy
    private AuthUserRoleFeign authUserRoleFeign;

    @Autowired
    @Lazy
    private UserFeign userFeign;

    @PutMapping(value = "/auth/user/role")
    RespResult update(@Validated @RequestBody AuthUserRoleUpdateInVo input) {
        return authUserRoleFeign.update(new AuthUserRoleUpdateInDto(input.getUserId(), input.getRoleIds()));
    }

    @GetMapping(value = "/auth/user/role/{userId}")
    RespResult<AuthRoleDetailOutVo> read(@PathVariable("userId") Integer userId) {
        RespResult<AuthUserRoleDetailDto> respResult = authUserRoleFeign.read(userId);
        if (!respResult._isOk()) {
            return RespResult.secByError(respResult.getCode(), respResult.getMsg());
        }
        RespResult<User> userRespResult = userFeign.read(userId);
        if (!respResult._isOk()) {
            return RespResult.secByError(respResult.getCode(), respResult.getMsg());
        }

        List<AuthRoleDetailOutVo> roleDetailOutVos = null;

        AuthUserRoleDetailDto userRoleDetail = respResult.getData();
        if (ArrayUtil.isEmpty(userRoleDetail.getRoles())) {
            roleDetailOutVos = userRoleDetail.getRoles().stream().map(x -> new AuthRoleDetailOutVo(x.getId(), x.getName(), null, null, null)).collect(Collectors.toList());
        }

        return RespResult.ok(new AuthUserRoleDetailOutVo(userRespResult.getData(), roleDetailOutVos));
    }

}
